package com.zhangxin.designmode.designpattern.prototype.v4;

import java.util.HashMap;
import java.util.List;

/**
 * @author zhangxin
 * @date 2022/5/6
 */
public class Demo {

    private HashMap<String, SearchWord> concurrentKeywords = new HashMap<>();
    private long lastUpdateTime = -1;

    public void refresh() {

        HashMap<String, SearchWord> newKeywords = new HashMap<>();

        //Deep Copy
        concurrentKeywords.forEach((key, searchWord) -> {
            SearchWord newSearchWord = new SearchWord(searchWord.getKeyword(),
                    searchWord.getCount(), searchWord.getLastUpdateTime());
            newKeywords.put(key, newSearchWord);
        });

        // 从数据库中取出更新时间>lastUpdateTime的数据，放入到newKeywords中
        List<SearchWord> toBeUpdateSearchWords = getSearchWords(lastUpdateTime);
        long maxNewUpdatedTime = lastUpdateTime;

        assert toBeUpdateSearchWords != null;
        for (SearchWord searchWord : toBeUpdateSearchWords) {
            if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {
                maxNewUpdatedTime = searchWord.getLastUpdateTime();
            }

            if (newKeywords.containsKey(searchWord.getKeyword())) {
                SearchWord oldSearchWord = newKeywords.get(searchWord.getKeyword());
                oldSearchWord.setCount(searchWord.getCount());
                oldSearchWord.setLastUpdateTime(searchWord.getLastUpdateTime());
            } else {
                newKeywords.put(searchWord.getKeyword(), searchWord);
            }
        }

        lastUpdateTime = maxNewUpdatedTime;
        concurrentKeywords = newKeywords;
    }

    private List<SearchWord> getSearchWords(long lastUpdateTime) {
        // TODO: 从数据库中取出更新时间>lastUpdateTime的数据
        return null;
    }
}
